﻿//using System;
//using System.Collections.Generic;
//using System.Configuration;
//using System.IO;
//using System.Linq;
//using System.Net;
//using System.Net.Http;
//using System.Net.Http.Headers;
//using System.Text;
//using System.Threading.Tasks;
//using System.Web.Script.Serialization;
//using System.Windows.Forms;
//using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;

//namespace AutoUpdate
//{
//    public class DownLoadMgr
//    {
//        private string userName = ConfigurationManager.AppSettings["UserName"];
//        private string password = ConfigurationManager.AppSettings["Password"];
//        //private string configPath       = ConfigurationManager.AppSettings["RemoteConfigPath"];
//        private string ServiceType = ConfigurationManager.AppSettings["ServiceType"];
//        private string remoteConfigPath = ConfigurationManager.AppSettings["RemoteConfigPath"];
//        private string remoteFileName = "updateConfig.txt";
//        JavaScriptSerializer convert = new JavaScriptSerializer();


//        private HttpClient client = new HttpClient();

//        /// <summary>
//        /// 获得服务端的版本码
//        /// </summary>      
//        /// <returns></returns>
//        public UpdateInfo GetUpdateInfo()
//        {
//            return GetUpdateInfo(int.Parse(ServiceType));
//        }


//        /// <summary>
//        /// 获得服务端的版本码
//        /// </summary>
//        /// <param name="configType">0:ftp;1:http</param>
//        /// <returns></returns>
//        public UpdateInfo GetUpdateInfo(int configType = 0)
//        {
//            UpdateInfo updateInfo = null;

//            #region 测试代码，用完删除
//            //var json = File.ReadAllText("UpdateConfig.dat");
//            //updateInfo = convert.Deserialize<UpdateInfo>(json);
//            //return updateInfo;
//            #endregion


//            var url = string.Format("{0}/{1}", remoteConfigPath, remoteFileName);
//            //ftp更新
//            if (configType == 1)
//            {
//                FtpWebRequest reqFTP;

//                try
//                {                    
//                    reqFTP = (FtpWebRequest)WebRequest.Create(new Uri(url));
//                    reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
//                    reqFTP.KeepAlive = false;
//                    reqFTP.UseBinary = true;
//                    reqFTP.UsePassive = true;
//                    reqFTP.Credentials = new NetworkCredential(userName, password);
//                    FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
//                    Stream ftpStream = response.GetResponseStream();
//                    StreamReader streamReader = new StreamReader(ftpStream, Encoding.UTF8);
//                    string data = streamReader.ReadToEnd();
//                    updateInfo = convert.Deserialize<UpdateInfo>(data);
//                    streamReader.Close();
//                    ftpStream.Close();
//                    response.Close();
//                }
//                catch (Exception ex)
//                {
//                    MessageBoxEx.Show(ex.Message, "自动更新失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
//                }

//            }
//            else if (configType == 2)
//            {
//                //http更新
//                if (!string.IsNullOrEmpty(this.userName) && !string.IsNullOrEmpty(this.password))
//                {
//                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes($"{this.userName}:{this.password}")));
//                } 
               
//                Uri address = new Uri(url);
//                var data = client.GetStringAsync(address).Result;//返回值
//                updateInfo = convert.Deserialize<UpdateInfo>(data);
//            }
//            return updateInfo;
//        }

//        /// <summary>
//        /// 下载文件
//        /// </summary>
//        /// <param name="remotePath"></param>
//        /// <param name="remoteFileName"></param>
//        /// <param name="localPath"></param>
//        /// <param name="localFileName"></param>
//        /// <returns></returns>
//        public bool Download(string remotePath, string remoteFileName, string localPath, string localFileName)
//        {
//            if(this.ServiceType == "1")
//            {

//            }
//            FileStream outputStream = null;
//            try
//            {
//                var localDir = AppDomain.CurrentDomain.BaseDirectory + localPath;
//                if (!Directory.Exists(localDir))
//                    Directory.CreateDirectory(localDir);

//                outputStream = new FileStream(string.Format("{0}\\{1}", localDir, localFileName), FileMode.Create);

//                var url = string.Format("{0}/{1}", remotePath, remoteFileName);
//                Console.WriteLine(url);
//                FtpWebRequest reqFTP = (FtpWebRequest)WebRequest.Create(new Uri(url));
//                reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
//                reqFTP.UseBinary = true;
//                reqFTP.KeepAlive = false;
//                reqFTP.Credentials = new NetworkCredential(this.userName, this.password);
//                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
//                Stream ftpStream = response.GetResponseStream();
//                int bufferSize = 2048, readCount = 0;
//                byte[] buffer = new byte[bufferSize];
//                while (true)
//                {
//                    readCount = ftpStream.Read(buffer, 0, bufferSize);
//                    if (readCount == 0)
//                        break;
//                    outputStream.Write(buffer, 0, readCount);
//                    //currentIndex += readCount;
//                    //totalIndex += readCount;
//                }
//                ftpStream.Close();
//                response.Close();
//                return true;
//            }
//            catch
//            {
//                return false;
//            }
//            finally
//            {
//                if (outputStream != null)
//                    outputStream.Close();
//            }
//        }
//    }
//}
